package com.twobu.twobuinsight.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.twobu.twobuinsight.dto.LoginRequest;
import com.twobu.twobuinsight.dto.LoginResponse;
import com.twobu.twobuinsight.dto.UserInfoResponse;
import com.twobu.twobuinsight.entity.User;
import com.twobu.twobuinsight.exception.BusinessException;
import com.twobu.twobuinsight.security.UserContext;
import com.twobu.twobuinsight.service.AuthService;
import com.twobu.twobuinsight.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // Redis中存储用户信息的key前缀
    private static final String TOKEN_KEY_PREFIX = "user:token:";

    // token有效期（秒）
    private static final long TOKEN_EXPIRE_TIME = 7200;

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 根据用户名查询用户
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, loginRequest.getUsername()));

        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 验证密码
//        String encryptedPassword = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());
        if (!user.getPassword().equals(loginRequest.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 生成token
        String token = "Bearer "+UUID.randomUUID().toString().replace("-", "");

        // 创建用户上下文
        UserContext userContext = UserContext.fromUser(user);

        // 将用户信息存入Redis，设置过期时间
        redisTemplate.opsForValue().set(TOKEN_KEY_PREFIX + token, userContext, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);

        // 构建登录响应
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUserId(userContext.getUserId());
        loginResponse.setUsername(userContext.getUsername());
        loginResponse.setRoleId(userContext.getRoleId());
        loginResponse.setTenantId(userContext.getTenantId());
        loginResponse.setToken(token);

        return loginResponse;
    }

    @Override
    public UserContext validateToken(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        String key =  TOKEN_KEY_PREFIX + token;
        Object o = redisTemplate.opsForValue().get(key);
        // 从Redis中获取用户信息
        UserContext userContext = (UserContext) redisTemplate.opsForValue().get(key);
        String s = stringRedisTemplate.opsForValue().get(key);
        log.info(key);
        log.info(s);

        if (userContext != null) {
            // 刷新token过期时间
            redisTemplate.expire(TOKEN_KEY_PREFIX + token, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
        }

        return userContext;
    }

    @Override
    public LoginResponse refreshToken(String token) {
        // 验证token
        UserContext userContext = validateToken(token);
        if (userContext == null) {
            throw new BusinessException("无效的token或已过期");
        }

        // 生成新token
        String newToken = UUID.randomUUID().toString().replace("-", "");

        // 将用户信息存入Redis，设置过期时间
        redisTemplate.opsForValue().set(TOKEN_KEY_PREFIX + newToken, userContext, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);

        // 删除旧token
        redisTemplate.delete(TOKEN_KEY_PREFIX + token);

        // 构建登录响应
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUserId(userContext.getUserId());
        loginResponse.setUsername(userContext.getUsername());
        loginResponse.setRoleId(userContext.getRoleId());
        loginResponse.setTenantId(userContext.getTenantId());
        loginResponse.setToken(newToken);

        return loginResponse;
    }

    @Override
    public void logout(String token) {
        if (token != null && !token.isEmpty()) {
            // 从Redis中删除token
            redisTemplate.delete(TOKEN_KEY_PREFIX + token);
        }
    }

    @Override
    public UserInfoResponse getCurrentUserInfo(Long userId) {
        // 根据userId查询用户信息
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserId, userId));

        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 转换为UserInfoResponse对象
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        userInfoResponse.setUserId(user.getUserId());
        userInfoResponse.setUsername(user.getUsername());
        userInfoResponse.setRoleId(user.getRoleId());
        userInfoResponse.setRealName(user.getRealName());
        userInfoResponse.setEmail(user.getEmail());
        userInfoResponse.setPhone(user.getPhone());
        userInfoResponse.setTenantId(user.getTenantId());
        userInfoResponse.setCreateTime(user.getCreateTime());
        userInfoResponse.setUpdateTime(user.getUpdateTime());

        return userInfoResponse;
    }
}
